import { Context } from "koa";

import allSqlAction from "../mysql";
import error from "../utils/error";

import config from "../config";
import jsonwebtoken from "jsonwebtoken";

import userModel from "../model/user";

export default class UserController {
  /* 新增 */
  public static async addUser(ctx: Context) {
    // console.log(ctx.request.body);
    let data = ctx.request.body;
    let a = (await userModel.addUser(data)) as any;

    ctx.status = 200;
    ctx.body = {
      msg: "添加成功",
      data: a,
      code: 200,
    };
  }

  /* 查询 */
  public static async getUser(ctx: Context) {
    // console.log(ctx);
    console.log(ctx.request.body);
    let a = (await userModel.getUser(ctx.request.body)) as any;

    ctx.status = 200;
    ctx.body = {
      msg: "查询成功",
      data: a,
      code: 200,
    };
  }

  /* 获取好友 */
  public static async getUserFriends(ctx: Context) {
    // console.log(ctx);
    const { userId } = ctx.request.body;
    let a = (await userModel.getUserFriendsModel(ctx.request.body)) as any;

    let b: any[] = [];

    for (const key in a) {
      if (Object.prototype.hasOwnProperty.call(a, key)) {
        const v = a[key];
        if (v.userIdA == userId) {
          let queryList = {
            id: v.userIdB,
            pageNum: 1,
            pageSize: 1,
          };
          let c = (await userModel.getUser(queryList)) as any;
          c[0].roomId = v.id;
          b.push(c[0]);
        }
        if (v.userIdB == userId) {
          let queryList = {
            id: v.userIdA,
            pageNum: 1,
            pageSize: 1,
          };
          let c = (await userModel.getUser(queryList)) as any;
          c[0].roomId = v.id;
          b.push(c[0]);
        }
      }
    }

    ctx.status = 200;
    ctx.body = {
      msg: "查询成功",
      data: b,
      code: 200,
    };
  }

  /* 登录 */
  public static async login(ctx: Context) {
    let contrast = [
      {
        name: "chatNum",
        errorWord: "闲迅号",
      },
      {
        name: "password",
        errorWord: "密码",
      },
    ];
    let errorWord = error.contrastError(contrast, ctx.request.body);
    if (!!errorWord) {
      ctx.body = {
        msg: errorWord,
        code: -1,
      };
      return;
    }

    let a = await userModel.userloginModel(ctx.request.body);

    if (Array.isArray(a)) {
      if (a.length == 0) {
        ctx.body = {
          msg: "用户名或密码错误",
          code: -2,
        };
        return;
      }
    }

    /* jwt 的设计思路 还是有点和实际业务可能有些区别，
      他不会通过 代码失效，只能通过时间失效 */
    /* 生成token */
    var info: any;
    if (Array.isArray(a)) {
      if (a.length != 0) {
        info = a[0];
      }
    }
    let token: any = jsonwebtoken.sign(info, config.JwtSecret, {
      expiresIn: "1d",
    });

    ctx.status = 200;
    ctx.body = {
      msg: "查询成功",
      data: a,
      token: token,
      code: 200,
    };
  }
}
